package org.demo.service.impl;

import java.util.List;

import org.demo.bean.Student;
import org.demo.service.StudentService;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业务层:StudentBeanImpl
 * 
 * @author
 * @date 2010-7-20
 * @file org.demo.service.impl.StudentServiceImpl.java
 */
@Transactional
public class StudentServiceImpl implements StudentService {

	@Autowired
	// @Resource //[在 jdk1.6下]
	private SessionFactory sessionFactory;

	/**
	 * true 保存
	 * 
	 * @param Student
	 */
	public void save(Student Student) {
		sessionFactory.getCurrentSession().persist(Student);
	}

	/**
	 * 修改
	 * 
	 * @param Student
	 */
	public void update(Student Student) {
		sessionFactory.getCurrentSession().merge(Student);
	}

	/**
	 * 删除
	 * 
	 * @param StudentId
	 */
	public void delete(int StudentId) {
		Object bean = sessionFactory.getCurrentSession().load(Student.class,
				StudentId);
		sessionFactory.getCurrentSession().delete(bean);
	}

	/**
	 * 删除所有
	 */
	public void deleteAll() {
		List<Student> list = getAll();
		for (int i = 0; i < list.size(); i++) {
			sessionFactory.getCurrentSession().delete(list.get(i));
		}
	}

	/**
	 * 获取
	 * 
	 * @param StudentId
	 * @return
	 */
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public Student get(int StudentId) {
		return (Student) sessionFactory.getCurrentSession().get(Student.class,
				StudentId);
	}

	/**
	 * 分页查询 [startRow < rowNum <= startRow + maxResult]
	 * 
	 * @param startRow
	 * @param maxResult
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List<Student> get(int startRow, int maxResult) {
		Query query = sessionFactory.getCurrentSession().createQuery(
				"from Student");
		query.setFirstResult(startRow);
		query.setMaxResults(maxResult);
		return query.list();
	}

	/**
	 * 获取全部
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true, propagation = Propagation.NOT_SUPPORTED)
	public List<Student> getAll() {
		return sessionFactory.getCurrentSession().createQuery("from Student")
				.list();
	}
}